<?php

namespace Packages\Statistics\Services;

use App\Tools\Common;
use Illuminate\Support\Facades\DB;

class StatisticsService
{

    /********************** 业务逻辑层 *********************/

    /**
     * 用户统计
     * @param array $data 
     * @return array
     */
    public function userCount($data)
    {

        $result = [];

        // 总数
        $result['total'] = DB::table('user.data_user_info')
            ->count();

        // 按天分组统计
        if (isset($data['byDay'])) {
            $result['byDay'] = DB::table('user.data_user_info')
                ->selectRaw("count(*), TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM-DD') as date")
                ->groupBy('date')
                ->orderBy('date', 'asc')
                ->get();
        }

        // 按月分组统计
        if (isset($data['byMonth'])) {
            $result['byMonth'] = DB::table('user.data_user_info')
                ->selectRaw("count(*), TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM') as date")
                ->groupBy('date')
                ->orderBy('date', 'asc')
                ->get();
        }

        // 按年分组统计
        if (isset($data['byYear'])) {
            $result['byYear'] = DB::table('user.data_user_info')
                ->selectRaw("count(*), TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY') as date")
                ->groupBy('date')
                ->orderBy('date', 'asc')
                ->get();
        }

        // 本月
        if (isset($data['thisMonth'])) {
            $month = strtotime(date('Y-m-01 00:00:00')); // 本月

            $result['thisMonth'] = DB::table('user.data_user_info')
                ->where('created_at', '>=', $month)
                ->count();
        }

        // 本周
        if (isset($data['thisWeek'])) {
            $weekStart = strtotime("this week Monday", time()); // 获取上一个周一的时间戳

            $result['thisWeek'] = DB::table('user.data_user_info')
                ->where('created_at', '>=', $weekStart)
                ->count();
        }

        // 昨日
        if (isset($data['yesterday'])) {
            $yesterdayStart = strtotime("yesterday"); // 获取昨日开始时间的时间戳
            $yesterdayEnd = strtotime("today") - 1; // 获取昨日结束时间的时间戳

            $result['yesterday'] = DB::table('user.data_user_info')
                ->whereBetween('created_at', [$yesterdayStart, $yesterdayEnd])
                ->count();
        }

        return $result;
    }
}
